package org.stvd.service.oauth.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.common.utils.ServiceResult;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.oauth.OauthAccessToken;
import org.stvd.entities.oauth.OauthRefreshToken;
import org.stvd.repository.oauth.OauthAccessTokenDao;
import org.stvd.repository.oauth.OauthRefreshTokenDao;
import org.stvd.service.base.impl.BaseServiceImpl;
import org.stvd.service.oauth.OauthAccessTokenService;

/**
 * 授权Token Service实现类
 * @author sunzhifeng
 */
@Service("oauthAccessTokenService")
public class OauthAccessTokenServiceImpl extends BaseServiceImpl<OauthAccessToken> 
    implements OauthAccessTokenService{

    @Resource(name = "OauthAccessTokenDao")
    private OauthAccessTokenDao oauthAccessTokenDao;
    @Resource(name = "OauthRefreshTokenDao")
    private OauthRefreshTokenDao oauthRefreshTokenDao;
    
    
    @Override
    public QueryResult<Map<String, Object>> queryAccessTokenResult(int start, int limit, String user_name, String client_id, String grant_type){
        return oauthAccessTokenDao.queryAccessTokenResult(start, limit, user_name, client_id, grant_type);
    }

    @Override
    @Transactional
    public ServiceResult<Map<String, Object>> deleteAccessToken(String tokenId) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(tokenId)) {
            serviceResult.setParamError("参数错误");
            return serviceResult;
        }
        OauthAccessToken oauthAccessToken = oauthAccessTokenDao.findByPk(OauthAccessToken.class, tokenId);
        if(oauthAccessToken==null) {
            serviceResult.setDataError("数据错误！");
            return serviceResult;
        }
        oauthAccessTokenDao.delete(OauthAccessToken.class, tokenId);
        oauthRefreshTokenDao.delete(OauthRefreshToken.class, oauthAccessToken.getRefreshToken());
        serviceResult.setMessage("删除成功！");
        return serviceResult;
    }
    
    @Override
    @Transactional
    public void deleteUserTokenByUserName(String userName) {
        List<Map<String, Object>> userTokenList = oauthAccessTokenDao.listAccessToken(userName);
        if(userTokenList != null && userTokenList.size() > 0) {
            for (Map<String, Object> tokenMap : userTokenList) {
                oauthAccessTokenDao.delete(OauthAccessToken.class, tokenMap.get("token_id"));
                if (tokenMap.containsKey("refresh_token") && oauthRefreshTokenDao.findByPk(OauthRefreshToken.class, tokenMap.get("refresh_token")) != null) {
                    oauthRefreshTokenDao.delete(OauthRefreshToken.class, tokenMap.get("refresh_token"));
                }
            }
        }
    }

}
